package cn.com.connext.scrm.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 用于临时发送的手机号和时间，用于验证使用
 */
public class MapUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(MapUtil.class);
    //存储发送的手机号和时间map
    private static Map<String,Long> sendMaps = new HashMap<String,Long>();

    private MapUtil(){}

    /**
     * 验证上次验证码是否过有效期
     * @param phone：手机号
     * @param time：最新的时间
     * @param seconds：有效时间(秒)
     * @return
     */
    public  static Boolean validationPeriod(String phone,Long time,int seconds){
        Long lastTime = sendMaps.get(phone);
        if ((null == lastTime) || ((time - lastTime) / 1000 > seconds) ){
            sendMaps.put(phone,time);
            LOGGER.info("put sendMap entry,phone：{},time：{}",phone,time);
            clearMapCache(phone,seconds);
            return true;
        }
        return false;
    }

    /**
     * 定时清除map中的发送信息
     * @param phone
     */
    private static void clearMapCache(String phone,int seconds){
        Timer timer = new Timer();
        TimerTask task =  new TimerTask() {
            @Override
            public void run() {
                sendMaps.remove(phone);
                LOGGER.info("remove sendMap entry,phone：{}",phone);
                cancel();
                timer.cancel();
                System.gc();
            }
        };
        timer.schedule(task,(seconds * 1000));
    }

}
